# encoding:utf-8

from ests import db
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash


class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    telephone = db.Column(db.String(11), nullable=False)
    username = db.Column(db.String(50), nullable=False)
    password = db.Column(db.String(100), nullable=False)
    add_time = db.Column(db.DateTime, index=True, default=datetime.now, unique=True)

    def __init__(self, *args, **kwargs):
        telephone = kwargs.get('telephone')
        username = kwargs.get('username')
        password = kwargs.get('password')

        self.telephone = telephone
        self.username = username
        self.password = generate_password_hash(password)  # 传进来的密码都会在这里进行加密

    def check_pwd(self, raw_password):
        result = check_password_hash(self.password, raw_password)  # 登录时进行比对解密
        return result

    def __repr__(self):
        return "<User %r>" % self.name


class Question(db.Model):
    __tablename__ = 'question'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    # utcnow（）获取的是服务器运行的时间
    # utcnow 每次创建模型时候获取当前的时间
    create_time = db.Column(db.DateTime, index=True, default=datetime.now, unique=True)
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    author = db.relationship('User', backref=db.backref('questions'))


class Answer(db.Model):
    __tablename__ = 'answer'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    content = db.Column(db.Text, nullable=False)
    question_id = db.Column(db.Integer, db.ForeignKey('question.id'))
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    create_time = db.Column(db.DateTime, default=datetime.now, unique=True)
    question = db.relationship('Question', backref=db.backref('answers'))
    author = db.relationship('User', backref=db.backref('answers'))
